import React, { Component } from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import Cookie from 'js-cookie'

import Frame from './Frame'
import { adminRoutes } from './routes'

const isLogin = () => Cookie.get('ycadmin')

const formatRoute = (routes) => {
  return routes.map(route => {
    if(route.children){
      return formatRoute(route.children)
    }
    return (
      <Route
        key={route.pathname}
        path={route.pathname}
        exact={route.exact}
        render={(routerProps) => {
          const YourComponent = React.lazy(() => import('.' + route.url))
          // TODO 判断用户权限
          return <YourComponent {...routerProps} />
        }}
      />
    )
  })
}

export default class App extends Component {
  render() {
    return (
      isLogin()
      ?
      <Frame>
        <Switch>
          {
            formatRoute(adminRoutes)
          }
          <Redirect to='/admin/home' from="/admin" exact />
          <Redirect to="/404" />
        </Switch>
      </Frame>
      :
      <Redirect to="/login" />
    )
  }
}
